﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Xml;

namespace Qpm.Automap.Core.UI
{
  public partial class SelectFile : Wizard.UI.InternalWizardPage
  {
    public SelectFile()
    {
      InitializeComponent();
      this.Banner.Subtitle = "Select project and output folder.";
      this.Banner.Title = "Step 1 of 4 - Select project and output folder";
      parameters.applicationDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);//Application.StartupPath;
      parameters.applicationDirectory = Path.Combine(parameters.applicationDirectory, parameters.DcmaFolder);
      parameters.projectContractFile = Path.Combine(parameters.applicationDirectory, parameters.projectContractFile);
      parameters.tempDirName = Path.Combine(parameters.applicationDirectory, parameters.tempDirName);
      parameters.configDirName = Path.Combine(parameters.applicationDirectory, parameters.configDirName);

      string outputFolder, schemaFolder = "";
      GetDefaultFolders(out outputFolder, out schemaFolder);
      t_outputFolder.Text = outputFolder;
      tb_schemaFolder.Text = schemaFolder;

      this.WizardNext += new Wizard.UI.WizardPageEventHandler(SelectFile_WizardNext);
    }

    void SelectFile_WizardNext(object sender, Wizard.UI.WizardPageEventArgs e)
    {
        if (parameters.importFile == null || parameters.importFile.Trim() == string.Empty)
        {
            MessageBox.Show("Please select a project file before continuing");
            e.Cancel = true;
            return;
        }
        string extension = Path.GetExtension(parameters.importFile);
        if (!extension.EndsWith("mpp") && !extension.EndsWith("xml"))
        {
            MessageBox.Show("Selected Project file must be a project file (extension .mpp) or an xml file");
            e.Cancel = true;
            return;
        }
        if (!Directory.Exists(t_outputFolder.Text))
        {
            MessageBox.Show("Selected output folder does not exist.  Please select an existing directory.");
            e.Cancel = true;
            return;
        }
        if (!SaveOutputFolder(t_outputFolder.Text))
        {
            e.Cancel = true;
        }
      if (!Directory.Exists(parameters.tempDirName))
      {
        Directory.CreateDirectory(parameters.tempDirName);
      }
      if (File.Exists(parameters.tempProjectFile))
        File.Delete(parameters.tempProjectFile);
      if (Path.GetExtension(parameters.importFile).EndsWith("mpp"))
      {
          ProjectAutomator.ConvertMppToXml(parameters.importFile, parameters.tempProjectFile);
      }
      else if (!Path.GetExtension(parameters.importFile).EndsWith("xml"))
      {
          MessageBox.Show("Please select an xml or project file.");
          e.Cancel = true;
      }
      else
      {
          parameters.tempProjectFile = parameters.importFile;
      }
      parameters.outputFolder = t_outputFolder.Text;
    }

    private void b_browseProjectFile_Click(object sender, EventArgs e)
    {

      openFileDialog1.ShowDialog();
      t_projectPath.Text = openFileDialog1.FileName;

      parameters.importFile = openFileDialog1.FileName;
      parameters.projectName = Path.GetFileNameWithoutExtension(parameters.importFile);
      parameters.tempProjectFile = Path.Combine(parameters.tempDirName, parameters.projectName + ".xml");
      parameters.configFile = Path.Combine(parameters.configDirName, parameters.projectName + ".xml");
    }

    private void SelectFile_SetActive(object sender, CancelEventArgs e)
    {
      this.Anchor = AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Bottom;
      SetWizardButtons(Wizard.UI.WizardButtons.Next);
    }

    private void GetDefaultFolders(out string outputFolder, out string schemaFolder)
    {
      XmlDocument doc = new XmlDocument();
      doc.Load(parameters.projectContractFile);
      XmlElement outputFolderElement = doc.SelectSingleNode("//OutputFolder") as XmlElement;
      XmlElement schemaFolderElement = doc.SelectSingleNode("//SchemaFolder") as XmlElement;
      outputFolder = outputFolderElement == null ? Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) : outputFolderElement.InnerText;
      schemaFolder = schemaFolderElement == null ? "C:\\" : schemaFolderElement.InnerText;
    }

    private bool SaveOutputFolder(string outputFolder)
    {
        string tempFileName = string.Format("{0:yyyYMMddHHmmss}", DateTime.Now) + "dcmatemp.txt";
        string tempFilePath = Path.Combine(t_outputFolder.Text, tempFileName);
        try
        {
            FileStream fs = File.Create(tempFilePath);
            fs.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("The UNCEFACT EVM Export Tool cannot write reports in the selected output folder");
            return false;
        }
        finally
        {
            File.Delete(tempFilePath);
        }
        XmlDocument doc = new XmlDocument();
        doc.Load(parameters.projectContractFile);
        XmlElement outputFolderElement = doc.SelectSingleNode("//OutputFolder") as XmlElement;
        if (outputFolderElement != null)
        {
            outputFolderElement.InnerText = outputFolder;
        }
        doc.Save(parameters.projectContractFile);
        return true;
    }

    private void SaveSchemaFolder(string schemaFolder)
    {
      XmlDocument doc = new XmlDocument();
      doc.Load(parameters.projectContractFile);
      XmlElement schemaFolderElement = doc.SelectSingleNode("//SchemaFolder") as XmlElement;
      if (schemaFolderElement != null)
      {
        schemaFolderElement.InnerText = schemaFolder;
      }
      doc.Save(parameters.projectContractFile);
    }

    private void b_browseOutputFolder_Click(object sender, EventArgs e)
    {
      if (t_outputFolder.Text.Trim().Length>0 && Directory.Exists(t_outputFolder.Text.Trim()))
      {
        folderBrowserDialog1.SelectedPath = t_outputFolder.Text.Trim();
      }
      folderBrowserDialog1.ShowDialog();
      t_outputFolder.Text = folderBrowserDialog1.SelectedPath;
    }

    private void button1_Click(object sender, EventArgs e)
    {
      if (tb_schemaFolder.Text.Trim().Length>0 && Directory.Exists(tb_schemaFolder.Text.Trim()))
      {
        folderBrowserDialog1.SelectedPath = tb_schemaFolder.Text.Trim();
      }
      folderBrowserDialog1.ShowDialog();
      tb_schemaFolder.Text = folderBrowserDialog1.SelectedPath;
      parameters.schemaFolder = folderBrowserDialog1.SelectedPath;

      SaveSchemaFolder(folderBrowserDialog1.SelectedPath);
    }

    private void label3_Click(object sender, EventArgs e)
    {

    }
  }
}
